<?php


namespace app\api\controller\v1;


use app\common\controller\Api;
use app\common\library\Sms;
use think\Db;
use think\Exception;
use think\Queue;
use think\Request;
use think\Validate;

class Hotel extends Api
{

    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    protected function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 补全单个图片的的URL，出现,只返回第一个
     * @param  $url
     * @return false|string|string[]|null
     */
    protected static function patchSingle($url)
    {
        if ($url == '') return null;
        if (stripos($url, 'ttp')) return $url;
        $time = time();
        if (stripos($url, ',')) {
            $arr = explode(',', $url);
            return Request::instance()->root(true) . $arr[0] . "?time=$time";
        } else {
            return Request::instance()->root(true) . $url . "?time=$time";
        }
    }

    /**
     * 获取、编辑酒店信息
     */
    public function real()
    {
        if ($this->request->isPost()) {
            $data['user_id']             = $this->auth->id;
            $data['hotel_name']          = $this->request->param('name');
            $data['hotel_contact']       = $this->request->param('contact');
            $data['hotel_phone']         = $this->request->param('phone');
            $data['hotel_license_image'] = $this->request->param('license_image');
            $data['hotel_mobile']        = $this->request->param('mobile');
            $data['captcha']             = $this->request->param('captcha');
            $data['createtime']          = time();

            $rule = [
                'hotel_name'          => 'require',
                'hotel_contact'       => 'require',
                'hotel_phone'         => 'require',
                'hotel_license_image' => 'require',
                'hotel_mobile'        => 'require',
                'captcha'             => 'require',
            ];

            $message = [
                'hotel_name.require'          => '请输入酒店名称',
                'hotel_contact.require'       => '请输入联系人',
                'hotel_phone.require'         => '请输入联系人联系电话',
                'hotel_license_image.require' => '请上传酒店营业执照',
                'hotel_mobile.require'        => '请输入手机号',
                'captcha.require'             => '请输入验证码',
            ];

            $validate = new Validate($rule, $message);
            !$validate->check($data) && $this->error($validate->getError());

            // 验证短信
            $sms = Sms::check($data['hotel_mobile'], $data['captcha'], 'send');
            !$sms && $this->error('认证失败，验证码不正确');

            // 检测文件是否存在
            !file_isset($data['hotel_license_image']) && $this->error('上传的营业执照文件不存在');

            try {
                Db::startTrans();
                $find                = Db::name('hotel')->where(['user_id' => $this->auth->id])->find();
                $data['status_real'] = 1;
                if ($find) {
                    $result = Db::name('hotel')->where(['user_id' => $this->auth->id])->update($data);
                } else {
                    $result = Db::name('hotel')->insert($data);
                }

                if ($result == 0) {
                    Db::rollback();
                    $this->error('认证失败，数据库更改失败');
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

            $this->success('认证成功');
        } elseif ($this->request->isGet()) {
            $result = Db::name('hotel')
                        ->field('id,hotel_name as name,hotel_contact as contact,hotel_phone as phone,hotel_license_image as license_image,hotel_image as image,hotel_content as content,status,status_real as `real`,hotel_mobile as mobile')
                        ->where(['user_id' => $this->auth->id])
                        ->find();
            if ($result) {
                $result['license_image_'] = self::patchSingle($result['license_image']);
                $result['image_']         = self::patchSingle($result['image']);
                $result['status_text']    = $result['status'] == 1 ? '正常' : '禁用';
                $result['content']        = self::patchContent($result['content']);
                $this->success('获取成功', $result);
            } else {
                $this->error('该用户不是酒店身份');
            }
        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }

    /**
     * 更换风采图
     */
    public function replace()
    {
        if ($this->request->isGet()) {
            $image = $this->request->param('image');
            !$image && $this->error('image 参数不能为空');

            // 检测文件是否存在
            !file_isset($image) && $this->error('上传的风采图文件不存在');

            $result = Db::name('hotel')->where(['user_id' => $this->auth->id])->update(['hotel_image' => $image]);

            if ($result == 0) {
                Db::rollback();
                $this->error('更换失败，数据库更新失败');
            }

            $this->success('更换成功', ['image_' => self::patchSingle($image), 'image' => $image]);
        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }

    /**
     * 更新手机号
     */
    public function setPhone()
    {
        if ($this->request->isGet()) {
            $data['hotel_mobile'] = $this->request->param('mobile');
            $data['captcha']      = $this->request->param('captcha');

            $data['hotel_mobile'] == null && $this->error('请填写手机号');
            $data['captcha'] == null && $this->error('请输入验证码');

            // 验证短信
            $sms = Sms::check($data['hotel_mobile'], $data['captcha'], 'send');
            !$sms && $this->error('验证码不正确');

            unset($data['captcha']);
            Db::name('hotel')->where(['user_id' => $this->auth->id])->update($data);
            $this->success('更新成功');
        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }

    /******************************************************************************************************************/

    /**
     * 酒店中心的兼职信息
     */
    public function job()
    {
        if ($this->request->isGet()) {
            $id = $this->request->param('id');

            $id == null && $this->error('id 参数不得为空');

            $result = Db::name('job')
                        ->where(['hotel_id' => $id, 'status' => ['in', '2,3'], 'job_date' => date('Y-m-d')])
                        ->field('id,job_type as type,status,job_arrival_datetime as arrival,job_people as sum,job_number as now')
                        ->select();

            if ($result) {
                foreach ($result as &$item) {
                    $item['type_text']   = Job::$job_type[$item['type']];
                    $item['status_text'] = Job::$status[$item['status']];
                    $item['speed']       = intval($item['now'] / $item['sum'] * 100) . '%';
                }
                $this->success('获取成功', $result);
            } else {
                $this->error('获取失败,您的酒店当天没有发布岗位');
            }
        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }

    /**
     * 兼职列表
     */
    public function list()
    {
        if ($this->request->isGet()) {
            $status   = $this->request->param('status');
            $job_date = $this->request->param('job_date');
            $id       = $this->request->param('id');

            ($id == null) && $this->error('id 参数不能为空');

            $where['hotel_id'] = $id;
            if ($status == '0') {
                $where['status'] = ['in', '2,3,4'];
            } else {
                $where['status'] = $status;
            }
            if ($job_date != null) {
                !strtotime($job_date) && $this->error('日期格式不正确');
                $where['job_date'] = $job_date;
            }

            $select = Db::name('job')
                        ->where($where)
                        ->order('job_date desc')
                        ->field('id,job_date,job_type as type,status,job_arrival_datetime as arrival,job_people as sum,job_number as now')
                        ->paginate(null, false, $this->paginate)
                        ->each(function ($item) {
                            $item['type_text']   = Job::$job_type[$item['type']];
                            $item['status_text'] = Job::$status[$item['status']];
                            $item['speed']       = intval($item['now'] / $item['sum'] * 100) . '%';
                            return $item;
                        });

            $arr       = $select->toArray();
            $uniqueArr = $this->uniqueArr($arr['data'], 'job_date');
            $result    = [];
            $index     = 0;
            foreach ($uniqueArr as $item) {
                $result[$index]['job_date'] = date("Y年m月", strtotime($item['job_date']));
                $result[$index]['job_day']  = date("d", strtotime($item['job_date']));
                foreach ($arr['data'] as $i) {
                    if ($i['job_date'] == $item['job_date']) {
                        $result[$index]['data'][] = [
                            "id"          => $i['id'],
                            "job_date"    => $i['job_date'],
                            "type"        => $i['type'],
                            "status"      => $i['status'],
                            "arrival"     => $i['arrival'],
                            "sum"         => $i['sum'],
                            "now"         => $i['now'],
                            "type_text"   => $i['type_text'],
                            "status_text" => $i['status_text'],
                            "speed"       => intval($i['now'] / $i['sum'] * 100) . '%',
                        ];
                    }
                }
                $index++;
            }
            $arr['data'] = $result;
            unset($index);
            unset($select);
            unset($uniqueArr);
            unset($result);
            $this->success('获取成功', $arr);
        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }

    /**
     * 兼职详情
     */
    public function details()
    {
        if ($this->request->isGet()) {
            $id = $this->request->param('id');

            ($id == null) && $this->error('id 参数不能为空');

            $result = Db::name('job')
                        ->where(['id' => $id])
                        ->field('job_type as type,status,job_arrival_datetime as arrival,job_people as sum,job_number as now,hotel_id')
                        ->find();

            if ($result) {
                $result['type_text']   = Job::$job_type[$result['type']];
                $result['status_text'] = Job::$status[$result['status']];
                $result['daogang']     = Db::name('order')->where(['job_id' => $id, 'status' => 2, 'company_first' => 1])->count('id');
                $result['wangong']     = Db::name('order')->where(['job_id' => $id, 'company_second' => 1])->count('id');

                $result['people'] = Db::name('order')
                                      ->alias('o')
                                      ->join('job j', 'j.id = o.job_id', 'left')
                                      ->join('user u', 'u.id = o.user_id', 'left')
                                      ->where(['j.id' => $id,'o.status'=>['<',7]])
                                      ->field('u.id,u.username,u.avatar,u.level,u.gender,u.age,o.id as order_id')
                                      ->select();

                foreach ($result['people'] as &$item) {
                    $item['level_text']  = User::$level[$item['level']];
                    $item['gender_text'] = User::$gender[$item['gender']];
                    $item['avatar']      = self::patchSingle($item['avatar']);
                }

                $this->success('获取成功', $result);
            } else {
                $this->error('获取失败,未找到兼职信息');
            }
        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }

    /**
     * 人员资料
     */
    public function userInfo()
    {
        if ($this->request->isGet()) {
            $user_id  = $this->request->param('user_id');
            $hotel_id = $this->request->param('hotel_id');
            $order_id = $this->request->param('order_id');

            ($user_id == null) && $this->error('user_id 参数不能为空');
            ($hotel_id == null) && $this->error('hotel_id 参数不能为空');
            ($order_id == null) && $this->error('order_id 参数不能为空');

            $query = Db::name('order')
                       ->where(['hotel_id' => $hotel_id, 'status' => '5'])
                       ->where('user_id = u.id')
                       ->field('count(id) as `count`')
                       ->buildSql();

            $result = Db::name('user')
                        ->alias('u')
                        ->join('order o', 'o.id = ' . $order_id, 'left')
                        ->where(['u.id' => $user_id])
                        ->field('u.id,u.avatar,u.mobile,u.username,u.age,u.gender,u.level,u.stature,u.health,u.health_image,u.level,u.introduce,u.disease,' . $query . 'as `count`,o.company_first_time,o.company_second_time,o.time_hour,o.duration_hour,o.fix_hour,o.status,o.is_renewal,o.job_id')
                        ->find();

            if ($result) {
                $find_order = Db::name('order')
                                ->alias('o')
                                ->join('hotel h', 'h.id = o.hotel_id', 'left')
                                ->where(['o.user_id' => $user_id, 'o.status' => 5])
                                ->field('h.hotel_name,o.order_job_type,o.order_job_date,o.job_id')
                                ->paginate(null, false, $this->paginate)
                                ->each(function ($item) {
                                    $item['order_job_type_text'] = Job::$job_type[$item['order_job_type']];
                                    $item['order_job_date']      = date('Y年m月d日', strtotime($item['order_job_date']));
                                    return $item;
                                });

                $result['job_status']          = Db::name('job')->where(['id' => $result['job_id']])->value('status');
                $result['company_first_time']  = $result['company_first_time'] ? date('Y-m-d H:i:s', $result['company_first_time']) : null;
                $result['company_second_time'] = $result['company_second_time'] ? date('Y-m-d H:i:s', $result['company_second_time']) : null;
                $result['duration_hour']       = $result['fix_hour'] ? $result['fix_hour'] : $result['duration_hour'];
                $result['total']               = $find_order->toArray()['total'];
                $result['per_page']            = $find_order->toArray()['per_page'];
                $result['current_page']        = $find_order->toArray()['current_page'];
                $result['last_page']           = $find_order->toArray()['last_page'];
                $result['order_id']            = intval($order_id);
                $result['status_text']         = Order::$status[$result['status']];
                $result['level_text']          = User::$level[$result['level']];
                $result['data']                = $find_order->toArray()['data'];
                $result['avatar']              = self::patchSingle($result['avatar']);
                $result['is_renewal']          = $result['is_renewal'] == 1 ? 2 : 1;
                unset($result['fix_hour']);
                unset($result['job_id']);
                $result['health_image'] = self::patchSingle($result['health_image']);
                $this->success('获取成功', $result);
            } else {
                $this->success('获取失败');
            }
        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }

    /******************************************************************************************************************/

    /**
     * 筛选报名
     */
    public function choice()
    {
        if ($this->request->isGet()) {
            $id = $this->request->param('id');

            ($id == null) && $this->error('id 参数不能为空');

            $where['hotel_id'] = $id;
            $where['status']   = 2;

            $select = Db::name('job')
                        ->where($where)
                        ->order('job_date desc')
                        ->field('id,job_date,job_type as type,job_arrival_datetime as arrival,job_people as sum,job_number as now')
                        ->paginate(null, false, $this->paginate)
                        ->each(function ($item) {
                            $item['type_text'] = Job::$job_type[$item['type']];
                            $item['speed']     = intval($item['now'] / $item['sum'] * 100) . '%';
                            return $item;
                        });

            $arr       = $select->toArray();
            $uniqueArr = $this->uniqueArr($arr['data'], 'job_date');
            $result    = [];
            $index     = 0;
            foreach ($uniqueArr as $item) {
                $result[$index]['job_date'] = date("Y年m月", strtotime($item['job_date']));
                $result[$index]['job_day']  = date("d", strtotime($item['job_date']));
                foreach ($arr['data'] as $i) {
                    if ($i['job_date'] == $item['job_date']) {
                        $result[$index]['data'][] = [
                            "id"        => $i['id'],
                            "type"      => $i['type'],
                            "arrival"   => $i['arrival'],
                            "sum"       => $i['sum'],
                            "now"       => $i['now'],
                            "type_text" => $i['type_text'],
                            "speed"     => $i['speed'],
                        ];
                    }
                }
                $index++;
            }
            $arr['data'] = $result;
            unset($index);
            unset($select);
            unset($uniqueArr);
            unset($result);
            $this->success('获取成功', $arr);
        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }

    /**
     * 筛选列表
     * 用户被禁用则不在前端显示
     */
    public function choiceList()
    {
        if ($this->request->isGet()) {
            $id    = $this->request->param('id');
            $order = $this->request->param('order');

            ($id == null) && $this->error('id 参数不能为空');
            ($order == null) && $this->error('order 参数不能为空');

            $order = ($order == 1) ? 'u.level desc' : 'u.level asc';

            $hotel_id = Db::name('job')->where(['id' => $id])->value('hotel_id');

            $query = Db::name('order')
                       ->where(['hotel_id' => $hotel_id, 'status' => '5'])
                       ->where('user_id = u.id')
                       ->field('count(id) as `count`')
                       ->buildSql();

            $status = [1 => '待处理', 2 => '已通过', 7 => '已拒绝'];
            $result = Db::name('order')
                        ->alias('o')
                        ->join('user u', 'u.id = o.user_id')
                        ->where(['u.status' => 1, 'o.status' => ['in', '1,2,7'], 'o.job_id' => $id])
                        ->field('o.user_id,o.status as order_status,o.id as order_id,u.username,u.avatar,u.gender,u.age,u.level,' . $query . 'as `count`')
                        ->order($order)
                        ->select();

            foreach ($result as &$item) {
                $item['hotel_id']    = $hotel_id;
                $item['level_text']  = User::$level[$item['level']];
                $item['status_text'] = $status[$item['order_status']];
                $item['sss']         = 1;
            }

            $this->success('获取成功', $result);
        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }

    /**
     * 筛选人员
     */
    public function choiceUser()
    {
        if ($this->request->isGet()) {
            $order_id = $this->request->param('order_id');
            $action   = $this->request->param('action');

            ($order_id == null) && $this->error('order_id 参数不能为空');
            ($action == null) && $this->error('action 参数不能为空');

            $action == 1 ? $status = 2 : $status = 7;
            $arr = explode(',', $order_id);


            try {
                Db::startTrans();
                $result = Db::name('order')->where(['id' => ['in', $order_id]])->update(['status' => $status]);

                if ($result != count($arr)) {
                    Db::rollback();
                    $this->error('操作失败，数据库调整失败');
                }

                $job_id = Db::name('order')->where(['id' => $arr[0]])->value('job_id');

                // 拒绝的话需要释放已报名人数
                if ($action == 2) {
                    Db::name('job')->where(['id' => $job_id])->setDec('job_number', count($arr));
                }
                Db::commit();
                $this->success('操作成功');
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }

    /******************************************************************************************************************/

    /**
     * 核销打卡
     */
    public function clock()
    {
        if ($this->request->isGet()) {
            $job_date = date('Y-m-d');
            $hotel_id = $this->request->param('id');

            ($hotel_id == null) && $this->error('id 参数不能为空');

            $where['hotel_id'] = $hotel_id;
            $where['status']   = 3;
            $where['job_date'] = $job_date;

            $select = Db::name('job')
                        ->where($where)
                        ->order('job_date desc')
                        ->field('id,job_date,job_type as type,job_arrival_datetime as arrival')
                        ->paginate(null, false, $this->paginate)
                        ->each(function ($item) {
                            $item['type_text'] = Job::$job_type[$item['type']];
                            $item['confirm']   = Db::name('order')->where(['status' => 2, 'job_id' => $item['id']])->count('id');
                            return $item;
                        });

            $arr       = $select->toArray();
            $uniqueArr = $this->uniqueArr($arr['data'], 'job_date');
            $result    = [];
            $index     = 0;
            foreach ($uniqueArr as $item) {
                $result[$index]['job_date'] = date("Y年m月", strtotime($item['job_date']));
                $result[$index]['job_day']  = date("d", strtotime($item['job_date']));
                foreach ($arr['data'] as $i) {
                    if ($i['job_date'] == $item['job_date']) {
                        $result[$index]['data'][] = [
                            "id"        => $i['id'],
                            "type"      => $i['type'],
                            "arrival"   => $i['arrival'],
                            "type_text" => $i['type_text'],
                            "confirm"   => $i['confirm'],
                        ];
                    }
                }
                $index++;
            }
            $arr['data'] = $result;
            unset($index);
            unset($select);
            unset($uniqueArr);
            unset($result);
            $this->success('获取成功', $arr);
        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }

    /**
     * 核销列表
     */
    public function clockList()
    {
        if ($this->request->isGet()) {
            $id    = $this->request->param('id');
            $order = $this->request->param('order');

            ($id == null) && $this->error('id 参数不能为空');
            ($order == null) && $this->error('order 参数不能为空');

            $order = ($order == 1) ? 'u.level desc' : 'u.level asc';

            $hotel_id = Db::name('job')->where(['id' => $id])->value('hotel_id');

            $query = Db::name('order')
                       ->where(['hotel_id' => $hotel_id, 'status' => '5'])
                       ->where('user_id = u.id')
                       ->field('count(id) as `count`')
                       ->buildSql();

            $result = Db::name('order')
                        ->alias('o')
                        ->join('user u', 'u.id = o.user_id')
                        ->where(['u.status' => 1, 'o.status' => 2, 'o.job_id' => $id])
                        ->field('o.user_id,o.status as order_status,o.id as order_id,u.username,u.avatar,u.gender,u.age,u.level,' . $query . 'as `count`,o.company_first,o.company_second,duration_hour,fix_hour,user_first,user_second')
                        ->order($order)
                        ->select();

            foreach ($result as &$item) {
                $item['hotel_id']       = $hotel_id;
                $item['level_text']     = User::$level[$item['level']];
                $item['status_text']    = Order::$status[$item['order_status']];
                $item['company_first']  = $item['company_first'] == 0 ? 1 : 2;
                $item['company_second'] = $item['company_second'] == 0 ? 1 : 2;
                $item['sss']            = 1;
                $item['hour']           = $item['fix_hour'] ? $item['fix_hour'] : $item['duration_hour'];
                unset($item['fix_hour']);
                unset($item['duration_hour']);
            }

            $this->success('获取成功', $result);
        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }

    /**
     * 核销人员
     */
    public function clockUser()
    {
        if ($this->request->isGet()) {
            $order_id = $this->request->param('order_id');
            $action   = $this->request->param('action');
            $location = $this->request->param('location');

            ($order_id == null) && $this->error('order_id 参数不能为空');
            ($action == null) && $this->error('action 参数不能为空');

            $arr = explode(',', $order_id);

            try {
                Db::startTrans();
                // 确认到岗
                if ($action == 1) {
                    $result = Db::name('order')->where(['id' => ['in', $order_id]])->update([
                        'company_first'          => 1,
                        'company_first_time'     => time(),
                        'company_first_location' => $location,
                    ]);
                    if ($result != count($arr)) {
                        Db::rollback();
                        $this->error('操作失败，数据库调整失败');
                    }
                } else { // 确认完工
                    $select = Db::name('order')->where(['id' => ['in', $order_id]])->select();
                    foreach ($select as $item) {
                        if ($item['company_first'] == 0) {
                            if (count($select) > 1) {
                                $name = Db::name('user')->where(['id' => $item['user_id']])->value('username');
                                $this->error("[$name]还没有确认到岗");
                            } else {
                                $this->error("请点击确认到岗");
                            }
                        }
                        // 计算工时
                        $company_hour = intval((time() - $item['company_first_time']) / 1800) / 2;
                        $data         = [
                            'company_second'          => 1,
                            'company_second_time'     => time(),
                            'company_second_location' => $location,
                            'duration_hour'           => $company_hour
                        ];
                        Db::name('order')->where(['id' => $item['id']])->update($data);
                    }
                }
                Db::commit();
                $this->success('操作成功', [date("Y-m-d H:i:s")]);
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }

    /**
     * 调整工作时间
     */
    public function clockFix()
    {
        if ($this->request->isGet()) {
            $param = $this->request->param('param');
            $param == null && $this->error('param 参数不能为空');

            $param = json_decode(htmlspecialchars_decode($this->request->param('param')), true);

            try {
                Db::startTrans();

                foreach ($param as &$item) {
                    $item['id']         = $item['order_id'];
                    $item['fix_hour']   = $item['hour'];
                    $item['updatetime'] = time();
                    unset($item['order_id']);
                    unset($item['hour']);
                    $result = Db::name('order')->update($item);
                    if ($result == 0) {
                        Db::rollback();
                        $this->error('调整失败');
                    }
                }
                Db::commit();
                $this->success('调整成功');
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }

    /******************************************************************************************************************/

    /**
     * 顺延用工
     */
    public function postpone()
    {
        if ($this->request->isGet()) {
            $job_date = date('Y-m-d');
            $hotel_id = $this->request->param('id');

            ($hotel_id == null) && $this->error('id 参数不能为空');

            $where['hotel_id'] = $hotel_id;
            $where['status']   = 3;
            $where['job_date'] = $job_date;

            $select = Db::name('job')
                        ->where($where)
                        ->order('job_date desc')
                        ->field('id,job_date,job_type as type,job_arrival_datetime as arrival')
                        ->paginate(null, false, $this->paginate)
                        ->each(function ($item) {
                            $item['type_text'] = Job::$job_type[$item['type']];
                            $item['renewal']   = Db::name('order')->where(['confirm_renewal' => 1, 'job_id' => $item['id']])->count('id');
                            return $item;
                        });

            $arr       = $select->toArray();
            $uniqueArr = $this->uniqueArr($arr['data'], 'job_date');
            $result    = [];
            $index     = 0;
            foreach ($uniqueArr as $item) {
                $result[$index]['job_date'] = date("Y年m月", strtotime($item['job_date']));
                $result[$index]['job_day']  = date("d", strtotime($item['job_date']));
                foreach ($arr['data'] as $i) {
                    if ($i['job_date'] == $item['job_date']) {
                        $result[$index]['data'][] = [
                            "id"        => $i['id'],
                            "type"      => $i['type'],
                            "arrival"   => $i['arrival'],
                            "type_text" => $i['type_text'],
                            "renewal"   => $i['renewal'],
                        ];
                    }
                }
                $index++;
            }
            $arr['data'] = $result;
            unset($index);
            unset($select);
            unset($uniqueArr);
            unset($result);
            $this->success('获取成功', $arr);
        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }

    /**
     * 顺延列表
     */
    public function postponeList()
    {
        if ($this->request->isGet()) {
            $id    = $this->request->param('id');
            $order = $this->request->param('order');

            ($id == null) && $this->error('id 参数不能为空');
            ($order == null) && $this->error('order 参数不能为空');

            $order = ($order == 1) ? 'u.level desc' : 'u.level asc';

            $hotel_id = Db::name('job')->where(['id' => $id])->value('hotel_id');

            $query = Db::name('order')
                       ->where(['hotel_id' => $hotel_id, 'status' => '5'])
                       ->where('user_id = u.id')
                       ->field('count(id) as `count`')
                       ->buildSql();

            $result = Db::name('order')
                        ->alias('o')
                        ->join('user u', 'u.id = o.user_id')
                        ->where(['u.status' => 1, 'o.status' => 2, 'o.job_id' => $id])
                        ->field('o.user_id,o.status as order_status,o.id as order_id,u.username,u.avatar,u.gender,u.age,u.level,' . $query . 'as `count`,is_renewal')
                        ->order($order)
                        ->select();

            foreach ($result as &$item) {
                $item['hotel_id']          = $hotel_id;
                $item['level_text']        = User::$level[$item['level']];
                $item['order_status_text'] = Order::$status[$item['order_status']];
                $item['sss']               = 1;
                $item['is_renewal']        = $item['is_renewal'] == 2 ? 1 : 2;
            }

            $this->success('获取成功', $result);
        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }

    /**
     * 顺延人员
     * 顺延人员 顺延天数
     * 判断是否存在顺延的job
     * 不存在添加job
     * 循环生成数据 [每顺延一天，多一条job]
     * insertAll
     */
    public function postponeUser()
    {
        if ($this->request->isGet()) {
            $param = $this->request->param('param');
            $param == null && $this->error('param 参数不能为空');

            // 解析参数
            $param = json_decode(htmlspecialchars_decode($this->request->param('param')), true);

            // 查找原始job
            $find_job = Db::name('job')->alias('j')->join('order o', 'j.id = o.job_id')->where(['o.id' => $param[0]['order_id']])->field('j.*')->find();

            try {
                Db::startTrans();
                foreach ($param as $item) {
                    $t = $item['day'];
                    for ($i = 1; $i <= $t; $i++) {
                        $find_job_renewal = Db::name('job')->where(['renewal_id' => $find_job['id'], 'job_date' => date("Y-m-d", strtotime('+ ' . $i . 'day'))])->find();
                        if ($find_job_renewal) { // 找到更新job的
                            $job_id = $find_job_renewal['id'];
                            Db::name('job')->where(['id' => $find_job_renewal['id']])->setInc('job_people');
                            Db::name('job')->where(['id' => $find_job_renewal['id']])->setInc('job_number');
                        } else { // 未找到添加job 同时发布定时任务
                            $job_data = [
                                'city_id'              => $find_job['city_id'],
                                'hotel_id'             => $find_job['hotel_id'],
                                'job_company_id'       => $find_job['job_company_id'],
                                'job_is_group'         => $find_job['job_is_group'],
                                'job_user_group_id'    => $find_job['job_user_group_id'],
                                'job_name'             => $find_job['job_name'],
                                'job_date'             => date("Y-m-d", strtotime('+ ' . $i . 'day')),
                                'job_type'             => $find_job['job_type'],
                                'job_top_start'        => $find_job['job_top_start'],
                                'job_top_end'          => $find_job['job_top_end'],
                                'job_down_start'       => $find_job['job_down_start'],
                                'job_down_end'         => $find_job['job_down_end'],
                                'job_price'            => $find_job['job_price'],
                                'job_time_hour'        => $find_job['job_time_hour'],
                                'job_people'           => 1,
                                'job_number'           => 1,
                                'job_arrival_datetime' => date("Y-m-d H:i:s", strtotime($find_job['job_arrival_datetime']) + 86400 * $i),
                                'job_condition'        => $find_job['job_condition'],
                                'job_hotel_introduce'  => $find_job['job_hotel_introduce'],
                                'job_location'         => $find_job['job_location'],
                                'job_route'            => $find_job['job_route'],
                                'createtime'           => time(),
                                'updatetime'           => time(),
                                'status'               => 3,
                                'renewal_id'           => $find_job['id'],
                            ];
                            $job_id   = Db::name('job')->insertGetId($job_data);
                            $data     = ['id' => $job_id, 'queue_update' => 1];

                            /**
                             * 定时将招聘改为进行中
                             */
                            // 上岗时间前10分钟
                            $time = strtotime($job_data['job_arrival_datetime']) - 600 - strtotime('now');
                            // 队列
                            $QueueRes = Queue::later($time, 'app\common\queue\Start', $data, 'job_start');
                            if ($QueueRes !== 1) {
                                $this->error('定时任务发布失败');
                            }

                            /**
                             * 定时判断订单异常还是结算
                             */
                            // 上岗时间+工作时间+6小时 自动结算
                            $time = strtotime($job_data['job_arrival_datetime']) + $job_data['job_time_hour'] * 3600 + 6 * 3600 - strtotime('now');
                            // 队列
                            $QueueResult = Queue::later($time, 'app\common\queue\End', $data, 'job_end');
                            if ($QueueResult !== 1) {
                                $this->error('定时任务发布失败');
                            }

                        }
                        // 查找原始订单
                        $find_order = Db::name('order')->where(['id' => $item['order_id']])->find();
                        $order_data = [
                            'number'          => time() . rand(10000, 99999),
                            'user_id'         => $find_order['user_id'],
                            'hotel_id'        => $find_order['hotel_id'],
                            'company_id'      => $find_order['company_id'],
                            'job_id'          => $job_id,
                            'user_mobile'     => $find_order['user_mobile'],
                            'order_job_type'  => $find_order['order_job_type'],
                            'order_job_date'  => date("Y-m-d", strtotime('+ ' . $i . 'day')),
                            'time_hour'       => $find_order['time_hour'],
                            'price'           => $find_order['price'],
                            'is_abnormal'     => 2,
                            'is_renewal'      => 1,
                            'confirm_renewal' => 1,
                            'createtime'      => time(),
                            'updatetime'      => time(),
                            'status'          => 2,
                        ];
                        // 更新原始订单
                        Db::name('order')->where(['id' => $item['order_id']])->update(['is_renewal' => 1]);
                        Db::name('order')->insert($order_data);
                    }
                }
                Db::commit();
                $this->success('顺延成功');
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }

    /******************************************************************************************************************/

    /**
     * 获取酒店介绍
     */
    public function content()
    {
        if ($this->request->isGet()) {
            $id = $this->request->param('id');
            $id == null && $this->error('id 参数不能为空');

            $result = Db::name('hotel')->find(['id' => $id]);
            if ($result) {
                $this->success('获取成功', self::patchContent($result['hotel_content']));
            } else {
                $this->error('未找到数据');
            }
        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }
}